// 用来启动后端服务的
const Vue = require('vue')
const express = require('express')

const fs = require('fs')

const isProd = process.env.NODE_ENV === 'production'
const setupDevServer = require('./build/setup-dev-server')

const app = express()

let renderer
let onReady

// 给/dist开头的请求资源文件---处理的是物理磁盘的资源
app.use('/dist', express.static('./dist'))


if (isProd) {
  const serverBundle = require('./dist/vue-ssr-server-bundle.json')
  const clientManifest = require('./dist/vue-ssr-client-manifest.json')

  // 配置模板
  renderer = require('vue-server-renderer').createBundleRenderer(serverBundle, {
    template: fs.readFileSync('./index.template.html', 'utf-8'),
    clientManifest
  })
} else {
  // 开发环境 -> 监视打包构建 -> 重新生成renderer渲染器
  onReady = setupDevServer(app, (serverBundle, template, clientManifest) => {
    renderer = require('vue-server-renderer').createBundleRenderer(serverBundle, {
      template: fs.readFileSync('./index.template.html', 'utf-8'),
      clientManifest
    })
  })
}


// const { renderToString } = renderer



const render = async function (req, res) {

  try {
    const html = renderer.renderToString({
      title: 'zwq',
      url: req.url,
      // meta1: '<meta name="viewport" describe="describe" content="zwqhaha"></meta>'
    }).then((html) => {
      console.log('html', html)
      // console.log('then')
      res.setHeader('Content-Type', 'text/html; charset=utf8')
      res.end(html)
    })
      .catch(err => {
        // console.log('err', err)
        console.log('err', err)
      })
  } catch (e) {
    console.log(e)
    return res.status(500).end('Internal Server Error.')
  }

}

// 服务端所有的路由都会进入到这里哦
app.get('*', isProd ? render : async (req, res) => {
  // 等待有了renderer渲染器后,再去调用render渲染
  await onReady
  render(req, res)
})

app.listen(3000)